//
//  EditInfoViewController.m
//  penzer
//
//  Created by caiyc on 2018/9/21.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "EditInfoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <IDLFaceSDK/FaceSDKManager.h>
#import "DetectionViewController.h"
@interface EditInfoViewController ()<UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>
@property(nonatomic,strong)UIImagePickerController *imagePicke;
@property(nonatomic,strong)UIImage *icons;
@property (weak, nonatomic) IBOutlet UIImageView *face_Img;
@property(assign)NSInteger sex;//0男1女
@property(nonatomic,strong)NSString *dateStr;
@property(nonatomic,strong)NSString *base_Str;
@property(assign)BOOL hasface;
@end

@implementation EditInfoViewController
-(void)setViewValue{
    NSDictionary *userDic = [XTool GetDefaultInfo:USER_INFO];
    NSLog(@".......%@",userDic);
    NSURL *url = [NSURL URLWithString:userDic[@"avatar"]];
    NSInteger sex = [userDic[@"sex"]integerValue];
    self.sex = sex;
    if(sex==1){
        
    }else{
        [self setButtonStyle:self.man_Btn andStyle:0];
        [self setButtonStyle:self.woman_Btn andStyle:1];
    }
    [self.icon_Img sd_setImageWithURL:url];
    self.height_Tf.text = userDic[@"height"];
    self.weight_Tf.text = userDic[@"weigth"];
    self.dateStr = userDic[@"birthday"];
    self.nick_Tf.text = [userDic[@"nickname"]isEqualToString:@""]?@"暂无":userDic[@"nickname"];
    self.nick_name.text = [userDic[@"nickname"]isEqualToString:@""]?@"暂无":userDic[@"nickname"];
    [self.birth_btn setTitle:userDic[@"birthday"] forState:UIControlStateNormal];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigation:1 andTitle:@"个人资料" andNaviColor:nil andTitleColor:nil];
    self.Top_Margin.constant = kTopHeight;
    self.hasface = 0;
    self.sex = 1;
    self.botom_ScroView.contentSize = CGSizeMake(screen_width, screen_height*1.8);
    self.botom_ScroView.showsVerticalScrollIndicator = 0;
    self.botom_ScroView.delegate = self;
    self.man_Btn.layer.cornerRadius = 5;
    self.woman_Btn.layer.cornerRadius = 5;
    self.finish.layer.cornerRadius = 5;
    self.editIcon_Btn.layer.cornerRadius = 5;
    self.editIcon_Btn.layer.borderColor = [UIColor blackColor].CGColor;
    self.editIcon_Btn.layer.borderWidth = 1;
    self.icon_Img.layer.cornerRadius = 45;
    self.icon_Img.layer.masksToBounds = 1;
    
    self.face_Img.userInteractionEnabled = 1;
    UITapGestureRecognizer *face = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeFace)];
    [self.face_Img addGestureRecognizer:face];
    
    self.date_Pickeer.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    self.date_Pickeer.datePickerMode = UIDatePickerModeDate;
    self.date_Pickeer.backgroundColor = viewcontrollerColor;
    [self.date_Pickeer addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
    self.date_Pickeer.hidden = 1;
    [self setViewValue];
    // Do any additional setup after loading the view from its nib.
}
-(void)changeFace{
    if ([[FaceSDKManager sharedInstance] canWork]) {
        
        NSString* licensePath = [[NSBundle mainBundle] pathForResource:FACE_LICENSE_NAME ofType:FACE_LICENSE_SUFFIX];
        [[FaceSDKManager sharedInstance] setLicenseID:FACE_LICENSE_ID andLocalLicenceFile:licensePath];
    }
    DetectionViewController* dvc = [[DetectionViewController alloc] init];
    dvc.completion=^(NSDictionary *images, UIImage *originImage){
        NSData* data = [[NSData alloc] initWithBase64EncodedString:[images[@"bestImage"] lastObject] options:NSDataBase64DecodingIgnoreUnknownCharacters];
        
        NSString *base_Str = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        self.base_Str = base_Str;
        [self uploadFace:base_Str];
        NSLog(@"base-------%@",base_Str);
        UIImage* bestImage = [UIImage imageWithData:data];
        self.face_Img.image = bestImage;
    };
    [self pushSecondVC:dvc];
}
-(void)uploadFace:(NSString *)base64{
    NSDictionary *param = @{@"image":base64,@"ta":@"face_add",@"op":@"member",@"ctrl":@"live",@"ac":@"member"};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            [WToast showWithText:@"人脸上传成功"];
            self.hasface = 1;
        }
    } failure:^(NSError *error) {
        
    }];
}
- (void)dateChange:(UIDatePicker *)datePicker
{
   NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *dateStr = [fmt stringFromDate:datePicker.date];
    self.dateStr = dateStr;
    [self.birth_btn setTitle:dateStr forState:UIControlStateNormal];
  }
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:1];
    self.date_Pickeer.hidden = 1;
}
//头像选择器
- (void)selectImge {
  
    
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //NSLog(@"选择的图片回调%@",info);
    NSLog(@"相册:%@",info);
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.icon_Img.image = image;
    self.icons = image;
    [self.imagePicke dismissViewControllerAnimated:YES completion:nil];
}
-(void)setButtonStyle:(UIButton *)btn andStyle:(NSInteger)type{
    if(type==0){
        //btn.layer.borderWidth=1;
        btn.layer.borderWidth = 1;
        btn.layer.borderColor = [UIColor blackColor].CGColor;
        btn.backgroundColor = [UIColor whiteColor];
    }else{
        // btn.layer.borderWidth=0;
        btn.layer.borderWidth = 0;
        //btn.layer.borderColor = [UIColor blackColor].CGColor;
        btn.backgroundColor = RGB(254, 220, 68);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)editIcons:(UIButton *)sender {
    [self selectImge];
}

- (IBAction)selectbirth:(UIButton *)sender {
    self.date_Pickeer.hidden = 0;
}
- (IBAction)Finish:(id)sender {
    [self.view endEditing:1];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", nil]];
    NSDictionary *paramter = @{@"c":@"entry",@"i":@"10",@"ac":@"member",@"ctrl":@"live",@"token":[XTool GetDefaultInfo:USER_INFO][@"token"],@"op":@"member",@"m":@"bz_activities",@"ta":@"edit_member",@"sex":[NSString stringWithFormat:@"%ld",(long)self.sex],@"weigth":self.weight_Tf.text,@"birthday":self.dateStr,@"height":self.height_Tf.text,@"nickname":self.nick_Tf.text};
    
    NSLog(@"发布参数：%@",paramter);
    
    [manager POST:BASE_URL parameters:paramter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //        for(NSInteger i = 0; i < self.image_Array.count; i++) {
        if(self.icons){
            NSData * imageData = UIImageJPEGRepresentation(self.icons, 0.5);
            // 上传的参数名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            //}
        }
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"上传回调===%@",responseObject);
        
        if([[responseObject objectForKey:@"message"][@"resultCode"]integerValue]==0)
        {
            [WToast showWithText:@"修改成功"];
            [self loadinfo];
        }
        else{
            [WToast showWithText:responseObject[@"message"][@"resultMessage"]];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WToast showWithText:@"更改失败请重试"];
        //  NSLog(@"上传失败原因===%@",error);
    }];
}
-(void)loadinfo{
    NSDictionary *param = @{@"ta":@"get_member",@"op":@"member",@"ac":@"member",@"ctrl":@"live"};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            NSDictionary *dic = [NSDictionary changeType:response[@"data"]];
            [XTool SaveDefaultInfo:dic Key:USER_INFO];
            [self.navigationController popViewControllerAnimated:NO];
        }
    } failure:^(NSError *error) {
        
    }];
}
- (IBAction)manSelct:(UIButton *)sender {
    self.sex = 1;
    [self setButtonStyle:sender andStyle:1];
    [self setButtonStyle:self.woman_Btn andStyle:0];
}

- (IBAction)womanSelect:(UIButton *)sender {
    self.sex = 2;
    [self setButtonStyle:sender andStyle:1];
    [self setButtonStyle:self.man_Btn andStyle:0];
}
@end
